package com.pdsu.graduation_design.listener;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pdsu.graduation_design.MainActivity;
import com.pdsu.graduation_design.domain.Agriculture;
import com.pdsu.graduation_design.utils.JsonUtil;
import com.pdsu.graduation_design.utils.Result;
import com.pdsu.graduation_design.views.AgricultureMessageDetailsActivity;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;

public class NewsAgricultureMessageListener implements AdapterView.OnItemClickListener {

    /**
     * 数据后台优化
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    private Context context;
    private List<Agriculture> agricultures;

    public NewsAgricultureMessageListener(Context context, List<Agriculture> agricultures) {
        this.context = context;
        this.agricultures = agricultures;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Toast.makeText(view.getContext(),"id"+id+position+view.getTransitionName(),Toast.LENGTH_SHORT).show();
        //当点击时，根据点击的位置get到list中agricultures中aid 和 uid
        //向后台服务器请求http得到结果。
        //根据结果启动Activity




        RequestParams requestParams=new RequestParams(MainActivity.URL+"/agriculture/findAgricultureUserByUID");
        requestParams.addParameter("uid",agricultures.get(position).getUid());
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    Result r= JsonUtil.JsonToObj(result,Result.class);

                    if (r.getCode().equals("200")){


                        Intent intent1=new Intent(context,AgricultureMessageDetailsActivity.class);
                        String agr_json= null;
                        agr_json = JsonUtil.ObjToJson(agricultures.get(position));

                        intent1.putExtra("agr_json",agr_json);
                        intent1.putExtra("username",r.getData().toString());
                        context.startActivity(intent1);

                    }else {

                    }

                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {


            }
        });




    }
}
